package models

import (
	"crypto/rand"
	"encoding/base64"
	"time"

	"gorm.io/gorm"
)

type AppConfig struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	Key       string    `gorm:"uniqueIndex;not null;size:100" json:"key"`
	Value     string    `gorm:"type:text;not null" json:"value"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

// GenerateRandomSecret 生成随机的 JWT Secret
func GenerateRandomSecret() (string, error) {
	bytes := make([]byte, 32)
	if _, err := rand.Read(bytes); err != nil {
		return "", err
	}
	return base64.URLEncoding.EncodeToString(bytes), nil
}

// GetOrCreateJWTSecret 获取或创建 JWT Secret
func GetOrCreateJWTSecret(db *gorm.DB) (string, error) {
	var config AppConfig
	err := db.Where("key = ?", "jwt_secret").First(&config).Error

	if err == gorm.ErrRecordNotFound {
		// 生成新的 JWT Secret
		secret, err := GenerateRandomSecret()
		if err != nil {
			return "", err
		}

		// 创建配置记录
		config = AppConfig{
			Key:   "jwt_secret",
			Value: secret,
		}
		if err := db.Create(&config).Error; err != nil {
			return "", err
		}
		return secret, nil
	} else if err != nil {
		return "", err
	}

	return config.Value, nil
}